package com.okay.util

import android.text.TextUtils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

class asd {
    /**
     * 8.0以上获取cpu的方式
     *
     * @return
     */
    val cpuDataForO: Float
        get() {
            var process: Process? = null
            try {
                process = Runtime.getRuntime().exec("top -n 1")
                val reader = BufferedReader(InputStreamReader(process.inputStream))
                var line: String
                var cpuIndex = -1
                while (reader.readLine().also { line = it } != null) {
                    line = line.trim { it <= ' ' }
                    line += "\n";//手动加上回车
                    if (TextUtils.isEmpty(line)) {
                        continue
                    }
                    val tempIndex = getCPUIndex(line)
                    if (tempIndex != -1) {
                        cpuIndex = tempIndex
                        continue
                    }
                    if (line.startsWith(android.os.Process.myPid().toString())) {

                        if (cpuIndex == -1) {
                            continue
                        }
                        val param = line.split("\\s+".toRegex()).toTypedArray()

                        for ((index,item) in param.withIndex()){
                            println("index $index : $item")
                        }
                        if (param.size <= cpuIndex) {
                            continue
                        }
                        var cpu = param[cpuIndex]
                        if (cpu.endsWith("%")) {
                            cpu = cpu.substring(0, cpu.lastIndexOf("%"))
                        }
                        return cpu.toFloat() / Runtime.getRuntime().availableProcessors()
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                process?.destroy()
            }
            return 0F
        }

    fun getCPUIndex(line: String): Int {
        if (line.contains("CPU")) {
            val titles = line.split("\\s+".toRegex()).toTypedArray()
            for (i in titles.indices) {
                if (titles[i].contains("CPU")) {
                    return i
                }
            }
        }
        return -1
    }
}